#include "Touch.h"
#include "Point.h"
#include <fcntl.h>
#include <unistd.h>
#include <atomic>
#include <thread>

// 静态成员变量定义

bool Touch::isInt = false; // 是否存在实例
atomic<int> Touch::currentTouchX{0};
atomic<int> Touch::currentTouchY{0};
atomic<bool> Touch::isTouching{false};

Touch::Touch(const char *path)
{
    if (isInt)
    {
        cout << "错误 重复初始化Touch设备" << endl;
        exit(-1);
    }
    fd = open(path, O_RDWR);
    if (fd == -1)
    {
        cout << "打开触摸屏文件失败" << endl;
        exit(-1);
    }

    running = true;
    eventThread = thread(&Touch::inputThread, this);
    isInt = true;

    cout << "触摸屏初始化成功" << endl;
}

Touch::~Touch()
{
    running = false;
    if (eventThread.joinable())
    {
        eventThread.join();
    }

    if (fd != -1)
    {
        close(fd);
    }

    isInt = false;
    cout << "Touch设备得到释放" << endl;
}

// 获取实时触摸位置
bool Touch::getCurrentTouchPosition(int &x, int &y)
{
    if (!isCurrentlyTouching())
        return false;

    x = currentTouchX.load();
    y = currentTouchY.load();
    return true;
}

bool Touch::isCurrentlyTouching()
{
    return isTouching.load();
}

void Touch::startLongPress(Container *container)
{
    if (longPressRunning)
        return;

    longPressRunning = true;
    longPressContainer = container;

    longPressThread = thread([this]()
                             {
        
        // 连续触发（每100ms一次）
        while (longPressRunning) {
            if (longPressContainer && longPressContainer->Event != nullptr) 
            {
                longPressContainer->Trigger_event();
            }
            this_thread::sleep_for(chrono::milliseconds(50));
        } });
}

void Touch::stopLongPress()
{

    longPressRunning = false;
    if (longPressThread.joinable())
    {
        longPressThread.join();
    }
    longPressContainer = nullptr;
}

void Touch::inputThread()
{
    cout << "touch线程1" << endl;
    struct input_event ev;
    Point current_pos;

    // 触摸屏和屏幕的尺寸比例
    const int TOUCH_WIDTH = 1024;
    const int TOUCH_HEIGHT = 600;
    const int SCREEN_WIDTH = 800;
    const int SCREEN_HEIGHT = 480;

    float scaleX = (float)SCREEN_WIDTH / TOUCH_WIDTH;
    float scaleY = (float)SCREEN_HEIGHT / TOUCH_HEIGHT;

    enum TouchState
    {
        STATE_IDLE,    // 空闲状态
        STATE_PRESSED, // 已按下状态
        STATE_RELEASED // 已松开状态
    };

    TouchState state = STATE_IDLE;
    // bool isTouching = false; // 添加触摸状态标志

    while (running)
    {
        ssize_t bytesRead = read(fd, &ev, sizeof(ev));

        if (bytesRead == sizeof(ev))
        {
            switch (ev.type)
            {
            case EV_ABS:
                switch (ev.code)
                {
                case ABS_X:
                    current_pos.set_pos_x((int)(ev.value * scaleX));
                    currentTouchX.store(current_pos.get_pos_x()); // 更新实时位置
                    break;
                case ABS_Y:
                    current_pos.set_pos_y((int)(ev.value * scaleY));
                    currentTouchY.store(current_pos.get_pos_y()); // 更新实时位置
                    break;
                }
                break;

            case EV_KEY:
                if (ev.code == BTN_TOUCH)
                {
                    if (ev.value == 1)
                    {
                        // 按下事件
                        state = STATE_PRESSED;
                        isTouching.store(true); // 标记为正在触摸
                        pressedContainer = nullptr;

                        if (rootContainer != nullptr)
                        {
                            // 纵深搜索被点击的容器
                            pressedContainer = rootContainer->getTouchedContainer(current_pos);

                            if (pressedContainer != nullptr && pressedContainer->hasEvent())
                            {
                                if (pressedContainer->get_Event_Type() == PRESS)
                                {
                                    pressedContainer->Trigger_event();
                                }
                                else if (pressedContainer->get_Event_Type() == LONG_PRESS)
                                {
                                    startLongPress(pressedContainer);
                                }
                            }
                        }
                    }
                    else
                    {
                        // 松开事件
                        isTouching.store(false); // 标记为停止触摸
                        stopLongPress();

                        state = STATE_RELEASED;
                        releasedContainer = nullptr;

                        if (rootContainer != nullptr)
                        {
                            // 纵深搜索被点击的容器
                            releasedContainer = rootContainer->getTouchedContainer(current_pos);

                            // 检查按下和松开是否为同一个容器
                            if (pressedContainer != nullptr &&
                                releasedContainer != nullptr &&
                                pressedContainer == releasedContainer)
                            {
                                if (pressedContainer->get_Event_Type() == CLICK)
                                {
                                    if (pressedContainer->hasEvent())
                                    {
                                        pressedContainer->Trigger_event();
                                    }
                                }
                            }
                        }

                        // 重置状态
                        pressedContainer = nullptr;
                        releasedContainer = nullptr;
                        state = STATE_IDLE;
                    }
                }
                break;

            case EV_SYN:
                break;
            }
        }
        // else
        // {
        //     cout << "touch线程6" << endl;
        //     this_thread::sleep_for(chrono::milliseconds(10));
        // }
    }
}
